package xyz.haijin.shiro.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xyz.haijin.shiro.model.CommonConstant;
import xyz.haijin.shiro.model.Result;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: haijin
 * @Date: 2022/07/16 18:08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = AuthorizationException.class)
    public Result<?> authenticationExceptionHandler(HttpServletRequest req, AuthorizationException e){
        log.error("发生业务异常！原因是：{}",e.getMessage());
        return Result.error(CommonConstant.FAIL,e.getMessage());
    }

    /**
     * 处理空指针的异常
     * @param req 请求
     * @param e 发生的异常
     * @return ignore
     */
    @ExceptionHandler(value =NullPointerException.class)
    public Result<?> exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return Result.error("系统异常");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<?> handleInvalidRequest(MethodArgumentNotValidException de) {
        String errMsg = de.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数校验不通过：[{}]", errMsg);
        return Result.error(CommonConstant.FAIL,errMsg);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleError(MissingServletRequestParameterException e) {
        log.error("缺少请求参数:[{}]", e.getMessage());
        String message = String.format("缺少必要的请求参数: %s", e.getParameterName());
        return Result.error(message);
    }

    /**
     * 处理其他异常
     * @param req 请求
     * @param e 发生的异常
     * @return ignore
     */
    @ExceptionHandler(value =Exception.class)
    public Result<?> exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return Result.error("系统异常");
    }


}
